package cn.minimelon.api.controller.common;

import cn.minimelon.api.constant.UserConstants;
import cn.minimelon.api.utils.file.MimeTypeUtils;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.DownloadedFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;

/**
 * 图片请求路径
 *
 * @author hiro
 */
@Slf4j
@Controller
public class ImageController extends BaseController {
    /**
     * 获取上传的图片
     */
    @Mapping(UserConstants.IMAGE_PREFIX + "/**")
    public DownloadedFile imageUrl(Context ctx) throws IOException {
        log.info("imageUrl:{}", ctx.uri().getPath());
        String filePath = ctx.uri().getPath().substring(UserConstants.IMAGE_PREFIX.length());
        String absPath = Solon.cfg().get("melon.profile") + filePath;
        String fileName = absPath.substring(absPath.lastIndexOf("/"));
        File desc = new File(absPath);
        if (desc.exists()) {
            return new DownloadedFile(MimeTypeUtils.IMAGE_JPEG, Files.newInputStream(desc.toPath()), fileName);
        }
        throw new FileNotFoundException(filePath);
    }
}
